<template>
    <div class="checkbox">
        <!-- group组合使用 -->
        <div v-if="isGroup" class="checkbox-box" @click="changeHandle">
            <div class="checkbox-child" v-show="isChecked">✔</div>
        </div>
        <!-- 单独使用 -->
        <div v-else class="checkbox-box" @click="changeHandle">
            <div class="checkbox-child" v-show="stateValue">✔</div>
        </div>
        <!-- 提示文案 -->
        <label class="label" @click="changeHandle">{{text}}</label>
    </div>
</template>
<script>
import emitter from '@/mixins/emitter.js'
import { findComponentUpWard } from '../../assets/js/findComponent.js'
export default {
  name: 'dj-checkbox',
  mixins: [emitter],
  props: {
    value: {
      type: Boolean,
      default: false
    },
    text: {
      type: String
    },
    label: {
      type: [String, Number]
    }
  },
  data () {
    return {
      parent: null,
      stateValue: this.value,
      isGroup: false,
      isChecked: false
    }
  },
  mounted () {
    //   查找父级是否有checkboxGroup 组件，如果有则是组合使用模式
    this.parent = findComponentUpWard(this, 'dj-checkbox-group')
    if (this.parent) {
      this.isGroup = true
      this.isChecked = this.parent.currentValue.includes(this.label)
    }
  },
  watch: {
    value (newVal) {
      this.stateValue = newVal
    },
    stateValue (newVal) {
      this.$emit('input', newVal)
      this.$emit('change', newVal)
      this.dispatch('dj-form-item', 'form-change', newVal)
    }
  },
  methods: {
    changeHandle () {
      if (this.parent) {
        this.groupChange()
      } else {
        this.singleChange()
      }
    },
    singleChange () {
      this.stateValue = !this.stateValue
    },
    groupChange () {
      this.isChecked = !this.isChecked
      this.parent.change(this.label, this.isChecked)
    }
  }
}
</script>
<style lang="scss" scoped>
.checkbox{
    $box-size:20px;
    font-size: 0;
    margin-bottom: 8px;
    .checkbox-box{
        vertical-align: middle;
        display: inline-block;
        width: $box-size;
        height: $box-size;
        border-radius: 4px;
        border: 1px solid #ccc;
        .checkbox-child{
            width: $box-size - 2px;
            height: $box-size - 2px;
            border-radius: 4px;
            border: 1px solid #fff;
            background: #2d8cf0;
            color: #fff;
            line-height: $box-size - 2px;
            text-align: center;
            transition: all .3s;
            font-size: 14px;
        }
    }
    .label{
        vertical-align: middle;
        display: inline-block;
        font-size: 14px;
        height: $box-size;
        line-height: $box-size;
        margin-left: 8px;
        color: #333;
    }
}
</style>
